package com.mingqijia.gassafety.job.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.Consumer;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.entity.auth.ManagerEntry;
import com.mingqijia.gassafety.db.mapper.ConsumerMapper;
import com.mingqijia.gassafety.db.mapper.DictionaryMapper;
import com.mingqijia.gassafety.db.mapper.auth.CompanyMapper;
import com.mingqijia.gassafety.job.request.CompanyRequest;
import com.mingqijia.gassafety.job.response.CompanyListResponse;
import com.mingqijia.gassafety.job.response.CompanyResponse;
import com.mingqijia.gassafety.job.service.CompanyService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.enums.YesNoEnum;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
   故障记录 服务类
 * </p>
 *
 * @author guoliang.lao
 * @since 2022-03-04
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyEntry> implements CompanyService {

    private final ConfigureHolder holder;
    @Autowired
    DictionaryMapper dictionaryMapper;
    @Autowired
    ConsumerMapper consumerMapper;

    /**
     * 数据来源，0-系统生成,1-vcc
     */
    private static final Integer source = 1;


    @Override
    public PageUtil<CompanyResponse> list(CompanyRequest req) {
        LambdaQueryWrapper<CompanyEntry> queryClause = new LambdaQueryWrapper<>();
        if (CollectionUtils.isEmpty(req.getId())) {
            if (StringUtils.hasText(req.getName())) {
                queryClause.like(CompanyEntry::getName, req.getName());
            }
            if (StringUtils.hasText(req.getType())) {
                queryClause.like(CompanyEntry::getType, req.getType());
            }
            if (StringUtils.hasText(req.getNature())) {
                queryClause.like(CompanyEntry::getNature, req.getNature());
            }
        } else {
            queryClause.in(CompanyEntry::getId, req.getId());
        }
        queryClause.eq(CompanyEntry::getIsDeleted, YesNoEnum.N.getCode())
                .ne(CompanyEntry::getType, Constants.DICTIONARY_PLATFORM)
                .eq(CompanyEntry::getSpId, req.getSpId());
        IPage<CompanyEntry> entries = this.page(new Page<>(req.getPage(), req.getPageSize()), queryClause);

        Map<String, DictionaryItemRespDTO> types = holder.getDictionaryInMap(Constants.CACHE_KEY_ORG_TYPE);
        Map<String, DictionaryItemRespDTO> natures = holder.getDictionaryInMap(Constants.CACHE_KEY_ORG_NATURE);

        List<CompanyResponse> responses = new ArrayList<>();
        for (CompanyEntry record : entries.getRecords()) {
            if (Objects.equals(record.getType(), Constants.DICTIONARY_PLATFORM)) {
                continue;
            }
            CompanyResponse response = new CompanyResponse();
            BeanUtil.copyProperties( record, response );
            // 变换显示中文
            response.setType(types.get(record.getType()).getName());
            response.setNature(Constants.STR_STRIKETHROUGH);
            if (StringUtils.hasText(record.getNature())) {
                response.setNature(natures.get(record.getNature()).getName());
            }
            if (Objects.equals(record.getParentId(), Constants.PLATFORM_SP)) {
                response.setParent(Constants.STR_SLASH);
            } else {
                response.setParent(Constants.STR_STRIKETHROUGH);
                CompanyEntry parent = this.getById(record.getParentId());
                if (!ObjectUtils.isEmpty(parent)) {
                    response.setParent(parent.getName());
                }
            }
            response.setState(Objects.equals(Constants.STR_ONE, response.getState()) ? "启用" : "停用");

            responses.add(response);
        }
        return PageUtil.init(entries, responses);
    }


    public String getOrgCode(String spId,String subsCode) {
        log.info("getOrgCode-job-spId:{}",spId);
        if (!StringUtils.isEmpty(subsCode)){
            Consumer consumer=consumerMapper.selectByOrgCode(subsCode,spId);
            log.info("getOrgCode-job-consumer:{}", JSONObject.toJSON(consumer));
            if (consumer!=null&&!StringUtils.isEmpty(consumer.getOrgCode()))
                return consumer.getOrgCode();
        }
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getId,spId).eq(CompanyEntry::getIsDeleted,0)
                .eq(CompanyEntry::getSource,source);
        List<CompanyEntry> list = this.list(queryWrapper);
        String orgCode = "";
        if (list.isEmpty()) {
            return "";
        } else {
            orgCode = list.get(0).getCode();
        }
        LambdaQueryWrapper<com.mingqijia.gassafety.db.entity.Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(com.mingqijia.gassafety.db.entity.Dictionary::getDictCode,"org_map").eq(com.mingqijia.gassafety.db.entity.Dictionary::getIsDeleted,0)
                .eq(com.mingqijia.gassafety.db.entity.Dictionary::getValue,orgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        if (dictList.isEmpty()) return orgCode;
        if (StringUtils.isEmpty(dictList.get(0).getDescription())) {
            return orgCode;
        } else {
            return dictList.get(0).getDescription();
        }
    }

    @Override
    public List<String> getOrgCodeBySubsCode(String spId) {
        log.info("getOrgCodeBySubsCode-param:{}",spId);
        List<String> orgCodes = new ArrayList<>();
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getId,spId).eq(CompanyEntry::getIsDeleted,0)
                .eq(CompanyEntry::getSource,source);
        List<CompanyEntry> list = this.list(queryWrapper);
        String orgCode = "";
        if (list.isEmpty()) {
            return orgCodes;
        } else {
            orgCode = list.get(0).getCode();
            orgCodes.add(orgCode);
        }
        LambdaQueryWrapper<Dictionary> dictQueryWrapper = new LambdaQueryWrapper<>();
        dictQueryWrapper.eq(Dictionary::getDictCode,"org_map_subsCode").eq(Dictionary::getIsDeleted,0)
                .eq(Dictionary::getValue,orgCode);
        List<Dictionary> dictList = dictionaryMapper.selectList(dictQueryWrapper);
        if (dictList.isEmpty()) return orgCodes;
        if (StringUtils.isEmpty(dictList.get(0).getDescription())) {
            return orgCodes;
        } else {
            dictList.forEach(dictionary -> {
                orgCodes.add(dictList.get(0).getDescription());
            });

            return orgCodes;
        }
    }

    @Override
    public List<CompanyListResponse> queryCompanyNameList(List<String> spIds) {
        LambdaQueryWrapper<CompanyEntry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyEntry::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(CompanyEntry::getId, spIds)
                .orderByDesc(CompanyEntry::getCreatedAt);
        List<CompanyEntry> list = this.list(queryWrapper);
        List<CompanyListResponse> resultList = list.stream().map(item -> {
            CompanyListResponse companyResponse = new CompanyListResponse();
            companyResponse.setSpId(item.getId());
            companyResponse.setName(item.getName());
            return companyResponse;
        }).collect(Collectors.toList());
        return resultList;
    }
}
